package com.icarus.quartz.service.impl;

import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.icarus.quartz.constant.QuartzJobConstant;
import com.icarus.quartz.detail.QuartzJobBaseDetail;
import com.icarus.quartz.entity.QuartzJob;
import com.icarus.quartz.entity.QuartzJobExample;
import com.icarus.quartz.entity.QuartzJobExample.Criteria;
import com.icarus.quartz.mapper.QuartzJobMapper;
import com.icarus.quartz.service.QuartzManager;

@Component
public class QuartzManagerImp implements QuartzManager {

	@Autowired
	private Scheduler scheduler;

	@Autowired
	private QuartzJobMapper quartzJobMapper;

	@Autowired
	private ApplicationContext applicationContext;

	public void add(QuartzJob jobInfo) throws Exception {
		TriggerKey triggerKey = TriggerKey.triggerKey(jobInfo.getJobId());
		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
		if (null == trigger) {
			// 不存在则创建一个
			JobDetail jobDetail = JobBuilder.newJob(QuartzJobBaseDetail.class)
					.withIdentity(jobInfo.getJobId()).build();
			JobDataMap jobDataMap = jobDetail.getJobDataMap();
			jobDataMap.put("jobInfo", jobInfo);
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
					.cronSchedule(jobInfo.getCronExpression())
					.withMisfireHandlingInstructionDoNothing();
			trigger = TriggerBuilder.newTrigger()
					.withIdentity(jobInfo.getJobId().toString())
					.withSchedule(scheduleBuilder).build();
			// 更新下次运行时间
			// updateNextRunTime(jobInfo, trigger.getFireTimeAfter(new Date()));
			scheduler.scheduleJob(jobDetail, trigger);
		}
	}

	public void init() {
		try {
			QuartzJobExample example = new QuartzJobExample();
			Criteria criteria = example.createCriteria();
			criteria.andJobStatusEqualTo(QuartzJobConstant.ENABLED);
			List<QuartzJob> jobs = quartzJobMapper.selectByExample(example);
			for (QuartzJob job : jobs) {
				add(job);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
